<?php
namespace app\wechat\controller;
use app\user\server\UserServer;
use app\wechat\service\Official;
use EasyWeChat\Factory;
use think\Controller;
use think\facade\Cache;
use think\facade\Log;

class Service extends Controller
{
    public $config;
    public $app;

    public function initialize()
    {
        parent::initialize();
        $config = config("official.");
        $option = [
            'app_id' => 'wx022d032893708397',
            'secret' => 'eba61ec2a2aeae9bcc6e1d21c6e1e1ec'
        ];
        //$option = get_option("wechat_official")['official'];
        $this->config= array_merge($config,$option);
        $this->app = Factory::officialAccount($this->config);
    }

    /**
     * Notes:验证服务器
     * User: chenping
     * email: 375129701@qq.com
     */
    public function service_vaildate()
    {
        //注册消息事件
        $this->app->server->push(function($message)
        {
            switch ($message['MsgType'])
            {
                case 'event':
                    $token = (new Official($this->config))->get_token()['access_token'];
                    $user = (new Official($this->config))->get_userinfo([
                        "access_token"=> $token,//$message['EventKey'],
                        "openid" => $message['FromUserName'],
                    ]);
                    $arr = [
                        "nickname" => $user['nickname'],
                        "avatar"   => $user['headimgurl'],
                        "username" =>"",
                        "phone"  =>"",
                        "openid"   => $user['openid'],
                        "sex"      => $user['sex'],
                        //绑定到开放平台才会显示此字段
                        "unionid"  => isset($user['unionid'])?$user['unionid']:''
                    ];
                    //qrscene_1625473136016,1625473136016
                    $message['EventKey'] = str_replace('qrscene_','',$message['EventKey']);
                    Log::debug("EventKey:".$message['EventKey']);

                    //用户注册 登录
                    $type =  substr($message['EventKey'], 0,13);

                    if($user && $type!="local_wechat_")
                    {
                        cache("user_".$message['EventKey'],$arr);
                        $user['access_token'] = $token;
                        $user['app_id'] = $this->config['app_id'];
                        (new UserServer())->wx_login($user);
                        return ''.$user['nickname'].',登录成功';
                    }

                    //账户绑定
                    if($user && $type=="local_wechat_")
                    {
                        $user['access_token'] = $token;
                        $user['app_id'] = $this->config['app_id'];
                        $arr = explode("local_wechat_",$message['EventKey']);
                        cache("bind_wechat_".$arr[1],$arr[1]);
                        $res = (new UserServer())->bind_wechat($user,$arr[1]);
                        if($res)
                        {
                            return ''.$user['nickname'].',你已成功绑定微信';
                        }
                    }

                    break;
                case 'text':
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                default:
                    return '欢迎关注新西公众号';
                    break;
            }
        });
        $response = $this->app->server->serve();
        $response->send();
    }

    /**
     * Notes:视频消息
     * User: chenping
     * email: 375129701@qq.com
     */
    protected function video()
    {

    }


    /**
     * Notes:生
     * User: chenping
     * email: 375129701@qq.com
     */
    protected function voice()
    {

    }

    /**
     * Notes:事件消息
     * User: chenping
     * email: 375129701@qq.com
     */
    protected function event()
    {

    }

    /**
     * Notes:文本消息
     * User: chenping
     * email: 375129701@qq.com
     */
    protected function text()
    {

    }

    /**
     * Notes:图片消息
     * User: chenping
     * email: 375129701@qq.com
     */
    protected function image()
    {

    }


    /**
     * Notes:获取二维码地址
     * User: chenping
     * email: 375129701@qq.com
     * return string
     */
    public function get_prcode_url($enk='')
    {
        //$token = (new Official($this->config))->get_token()['access_token'];
        if(!$enk) $enk = getMsecTime();
        session("login",$enk);
        $res =  $this->app->qrcode->temporary($enk, 6 * 24 * 3600);
        return $this->app->qrcode->url($res['ticket']);
    }


}